CFML (ColdFusion Markup Language)
ColdFusion 主要功能:
A DYNAMIC LANGUAGE - WHAT DOES IT MEAN?
<cfscript>
number1 = 5;
number2 = 6;
number3 = "7";
answer1 = number1 + number2;
answer2 = number1 + number3;
</cfscript>
<cfoutput>
<p>5 + 6 = #answer1#</p>
<!-- result: 11 -->
<p>5 + "7" = #answer2#</p>
<!-- result: 12 -->
</cfoutput>1
isnumeric(variabletocheck)
與 int(theNumberToCast)
writeOutput()
; CF Tag: <cfoutput>
listLen()
: 回傳list的item數listAppend()
: 新增item在list 最後listPrepend()
:在list 最前面增加itemlistInsertAt()
: 再選擇的位置增加itemMyList is "1,2,,3,,4,,,5"
list functions treat it the same as "1,2,3,4,5"
listToArray()
, arrayToList()
: array與list 轉換arrayAvg()
, arraySum()
, arrayMax()
, arrayMin()
, arraySort()
: 平均數, 總和, 最大值, 最小值, 排序structCount()
:structKeyExists()
:structInsert()
: 在struct 最後增加item
structAppend()
: 結合兩個structs,不是增加structstructKeyList()
, structKeyArray()
: 傳回所有的keys以list, array的形式structFindKey()
, structFindValue()
: 傳回要找的值的array<!--- create initial array --->
<cfset baseArray = ArrayNew(1)>
<!--- create and populate struct --->
<cfset childStruct = StructNew()>
<cfset childStruct.fruit = "Bananas">
<cfset childStruct['veggie'] = "Zuchinni">
<cfset structInsert(childStruct,'meat','Steak')>
<!--- add struct to array --->
<cfset arrayAppend(baseArray,childStruct)>
<!--- 當資料append 在struct時 --->
<cfset arrayAppend(baseArray,'this is a test')>
<cfdump var=#baseArray#>
Ref: Data-Types Tutorials
Len()
: 回傳字串數量,空格會被計算,範例 Len("Hello ")
回傳6,Trim()
: 刪除空格,範例Trim("Hello ")
回傳 HelloReplace()
: 取代
Replace("Hello", "e", "")
回傳 HlloReplace("Good Morning!", "o", "e", "All")
回傳 Geed Merning!RemoveChars(字串,起始點,距離)
: 刪除字串,範例: RemoveChars("hello bob", 2, 5)
回傳hbobMid(字串,起始點,距離)
: 截取,範例: Mid("Welcome to CFML Jumpstart",4,12)
回傳 come to CFML<cfset today = DayOfWeekAsString(DayOfWeek((now())))>
<!--- 字串聯值 --->
<cfset message = "Happy " & today & "!">
<!--- 字串插值 --->
<cfset message="Happy #today#!">
<cfoutput>
#message#
</cfoutput>
Ref: Editing-Strings Tutorials
Now()
, CreateDate (Y,M,D)
, CreateTime (H,M,S)
, CreateDateTime (Y,M,D,H,M,S)
, IsDate (date)
DateFormat ("date" [, "mask" ])
, TimeFormat ("time"[, "mask" ])
, DateTimeFormat ("date/time"[, "mask" ])
datepart
, number
, date
Year("date")
, Quarter("date")
, Month("date")
, Week("date")
, Day("date")
, Hour("date")
, Minute("date")
, Second("date")
DaysInYear("date")
, DaysInMonth("date")
, FirstDayOfMonth("date")
, DayOfYear("date")
, DayOfWeek("date")
MonthAsString(month_number [, locale])
, DayOfWeekAsString(day_of_week [, locale])
: Locale 預設是US
<cfset DateNow = now()>
<cfoutput>
Full Date: #datetimeformat(DateNow)#<br/>
Year: #year(dateNow)# <br/>
Quarter: #Quarter(dateNow)# <br/>
Month: #Month(dateNow)# <br/>
Week: #Week(dateNow)# <br/>
Day: #Day(dateNow)# <br/>
Minute: #Minute(dateNow)# <br/>
Second: #Second(dateNow)# <br/>
<br/>
DaysInYear: #DaysInYear(dateNow)# <br/>
DaysInMonth: #DaysInMonth(dateNow)# <br/>
<br/>
FirstDayOfMonth: #FirstDayOfMonth(dateNow)# <br/>
DayOfYear: #DayOfYear(dateNow)# <br/>
DayOfWeek: #DayOfWeek(dateNow)# <br/>
<br/>
MonthAsString: #MonthAsString(month(dateNow))# <br/>
DayOfWeekAsString: #DayOfWeekAsString(DayOfWeek(dateNow))# <br/>
</cfoutput>
createSpane(Days,Hours,Minutes,Seconds)
: 建立時間區間的物件<cfset startDate = "01-10-2016">
<cfset endDate="01-31-2016">
<cfset stepPeriod = createTimeSpan(1,0,0,0)>
<cfloop from = "#startDate#" to = "#endDate#" step="#stepPeriod#" index = "tempDate">
<cfoutput>
#dateformat(tempDate, "mm-dd-yyyy")#<br>
</cfoutput>
</cfloop>
DateCompare("date1", "date2" [,"datePart"])
: 日期比較
DateDiff("datepart", "date1", "date2")
: 日期相差
<cfset dateNow = now()>
<cfset dateNext = dateAdd("d", 5, dateNow)>
<cfoutput>
#dateNow#<br>
#dateNext#<br>
DateCompare: #DateCompare("#dateNow#", "#dateNext#")#<br>
DateDiff: #DateDiff("d", #dateNow#, #dateNext#)#
</cfoutput>
fix()
: 當日期類的資料備存成其他的資料型態,如number, string時,!coldfusion提供轉換的Function
<h3>Date</h3>
<cfset date = "12-12-2013">
<cfoutput>
String: #date#<br/>
<cfset dateMod = date + 0>
Number: #(dateMod)#<br/>
Next Day: #dateformat(dateMod + 1,"mm-dd-yyyy")#<br/>
<h3>Day & Time</h3>
<cfset dTime = "01-12-2013 1:00 PM">
String: #dTime#<br/>
Decimal: #(dTime + 0)#<br/>
<h3>Date Fix</h3>
<!--- Demonstrating the fix function --->
Date & Time: #datetimeformat(dTime)#<br/>
Date w/o Time: #datetimeformat(fix(dTime))#<br/>
</cfoutput>
CreateODBCDate(date)
: 日期物件,標準化的ODBC日期格式CreateODBCTime(date)
: 時間物件,標準化的ODBC時間格式CreateODBCDateTime(date)
: 日期-時間物件, ODBC 標準格式<cfquery name="get_events" datasource="test">
SELECT * FROM events_table
where date < <cfqueryparam value="#createODBCDate('12/15/2103')#" cfsqltype="cf_sql_date">
</cfquery>
<cfset dateNow = now()>
<cfoutput>
Date: #CreateODBCDate(dateNow)#<br/>
Time: #CreateODBCTime(dateNow)#<br/>
Date & Time: #createODBCDateTime(dateNow)#<br/>
</cfoutput>
Ref: WORKING WITH DATES & TIMES Tutorials
Looping Types: Numbers, Lists, Arrays, Structs, Query, Dates, Times, File (loops line by line of file)
<cfloop from="1" to="100" index="i">
<cfoutput>#i#</cfoutput>
<br/>
</cfloop>
<cfset shoppinglist = "apples, banannas, grapes">
<cfloop list="#shoppinglist#" index="i">
<cfoutput>#i#</cfoutput>
<br/>
</cfloop>
<cfset shoppinglist = ["apples", "banannas", "grapes"]>
<!-- from 手法 -->
<cfloop from=1 to="#arrayLen(shoppinglist)#" index="i">
<cfoutput>#shoppinglist[i]#</cfoutput>
<br/>
</cfloop>
<!-- array 手法 -->
<cfloop array="#shoppinglist#" index="i">
<cfoutput>#i#</cfoutput>
<br/>
</cfloop>
collection
,用item
取代index
<cfset shoppinglist = StructNew()>
<cfset shoppinglist['apples'] = 'green'>
<cfset shoppinglist['bannanas'] = 'yellow'>
<cfset shoppinglist['grapes'] = 'purple'>
<cfloop collection="#shoppinglist#" item="i">
<!--- in this example "i" is the key --->
<cfoutput>#i# - #shoppinglist[i]#</cfoutput>
<br/>
</cfloop>
myQuery
取代item
, index
<cfoutput>
作為輸出myQuery.RecordCount
: 回傳 rows的數量 (常用)myQuery.CurrentRow
: 當前在iterater 的rowsmyQuery.ColumnList
: query欄 放入用逗號分隔的list 中<cfscript>myQuery=queryNew("fruit,color","Integer,Varchar",
[ ["apples","green"], ["banannas","yellow"], ["grapes","purple"] ]);
</cfscript>
<cfdump var=#myQuery# label="Shopping List"><br/>
<cfoutput>Record Count: #myQuery.RecordCount#</cfoutput><br/>
<cfoutput>Column List: #myQuery.ColumnList#</cfoutput><br/>
<!--- Loop over list of items --->
<cfloop query="#myQuery#">
<!--- current row of the loop --->
<cfoutput>#myQuery.CurrentRow#</cfoutput>
<cfoutput>#myQuery.fruit# - #myQuery.color#</cfoutput>
<br/>
</cfloop>
arrayNew()
: 建立array,arrayLen()
: 查array裡面items數量(INITIALIZATION; TEST CONDITION; ITERATOR) { LOOP STATEMENTS }
<cfloop index="INITIALIZATION" from="INITIALIZATION" to="TEST CONDITION" [, step=""]></cfloop>
<cfset variables.arLoopie = ["Blinky", "Pinky", "Inky", "Clyde", "Sue"] />
<cfset variables.loopieLen = arrayLen(variables.arLoopie) />
<h5>Index Looping Results</h5>
<div><em>using tags</em></div>
<cfoutput>
<cfloop index="variables.i" from="1" to="#variables.loopieLen#">
Now we have #variables.arLoopie[variables.i]#<br/>
</cfloop>
</cfoutput>
<hr/>
<div><em>using cfscript</em></div>
<cfscript>
for(variables.x=1; variables.x <= variables.loopieLen; variables.x++ ) {
writeOutput("So, now we have " & variables.arLoopie[variables.x] & "<br/>");
}
</cfscript>
from
, to
預設 from="1" to="#arrayLen(arMyArray)#"
<cfset variables.arLoopie = ["Blinky", "Pinky", "Inky", "Clyde", "Sue"] />
<h5>For-In Looping Results</h5>
<div><em>using tags</em></div>
<cfoutput>
<cfloop index="variables.cur" array="#variables.arLoopie#">
Now we have #variables.cur#<br/>
</cfloop>
</cfoutput>
<hr/>
<div><em>using cfscript</em></div>
<cfscript>
for(variables.scriptCur in variables.arLoopie) {
writeOutput("So, now we have " & variables.scriptCur & "<br/>");
}
</cfscript>
for(variables.x=variables.loopieLen; variables.x >= 1; variables.x-- )
<cfloop index="variables.i" from="#variables.loopieLen#" to="3" step="-1"></cfloop>
arraySort(array, "type", "asc/desc")
,array會被重新排列arrayFind(array, "search text")
回傳 array 裡的index,"0"代表不存在array裡arrayPrepend(array, "element")
; arrayPend(array, "element")
query object
或是 array of structs
<cfscript>
variables.arLittleMermaidFans = [
{name="Biff Brubaker", age=37, favsong="Part of Your World"},
{name="Tammy Temperance", age=59, favsong="Under the Sea"},
{name="Jim Jabroni", age=12, favsong="Kiss the Girl"}
];
</cfscript>
<cfoutput>
<table>
<tr>
<th>Name</th>
<th>Favorite Song</th>
<th>Age</th>
</tr>
<cfloop index="variables.curFan" array="#variables.arLittleMermaidFans#">
<tr>
<td>#variables.curFan.name#</td>
<td>#variables.curFan.favsong#</td>
<td>#variables.curFan.age#</td>
</tr>
</cfloop>
</table>
</cfoutput>
listToArray()
: 讓list 變成 array (這個function 的效率不好,別太常使用)<cfscript>
variables.sillyString = "Sent to spy on a cuban talent show;First stop:Havanago-go!";
variables.arSilly = listToArray(variables.sillyString, " ;:");
writeDump(variables.arSilly);
</cfscript>
Ref: ARRAYS IN COLDFUSION Tutorials
cfscript與cf tag,範例:
```javascript
<cfscript>
if ( true ) {
WriteOutput( 'The truth is out there.' );
}
</cfscript>
<br />
<cfif true >
The truth is out there!
</cfif>
```
Conditional-Statements Tutorials
範例:
```javascript
<cfset how_you_feel = "Kaput">
<cfswitch expression="#how_you_feel#">
<cfcase value="Slightly Happy">
<cfset what_we_should_do = "Eat a bowl of ice cream!">
</cfcase>
<cfcase value="Kaput">
<cfset what_we_should_do = "Stop thinking and go to bed!">
</cfcase>
<cfdefaultcase>
<cfset what_we_should_do = "Stop being such a robot and learn to feel again! ">
</cfdefaultcase>
</cfswitch>
<h3>What should I do with this free time!!! ahhhhhhh!</h3>
<cfoutput>
#what_we_should_do#
</cfoutput>
<!-- result
What should I do with this free time!!! ahhhhhhh!
Stop thinking and go to bed!
-->
```
Duplicate()
: CFML struct called by refereced,當用structA=structB
時,改變structB的內容也會一起改變structA的內容,必須用Duplicate()
,才會複製出兩個不相影響的struct variable
structLeyArray()
: 傳回struct裡所有的 keys 用array輸出<cfscript>
variables.structCoke = {
hasDiet = true,
slogan = "something about polar bears and santa",
fakeFact = "actually made out of real polar bear"
};
variables.structPepsi = Duplicate( variables.structCoke);
variables.structPepsi.slogan = "Uh-Huh!";
variables.structPepsi.fakeFact = "Ray Charles was caught with a Diet Coke once, but Pepsi covered it up";
variables.structPepsi.reasonToHate = "tastes like bacon"
writeOutput("Coke: " & arrayToList(structKeyArray(variables.structCoke)) & "<br/>");
writeOutput("Pepsi: " & arrayToList(structKeyArray(variables.structPepsi)) & "<br/>");
</cfscript>
structNew()
or {}
: 建立一個空的struct,keys 是不區分大小寫的,除非使用quotes""
包起來去命名,不然 Coldfusion 預設會把 keys 都變大寫MYSTRUCT.MYKEY
; Bracket Notation MYSTRUCT["MYKEY"]
,有一些特殊字元會讓 Dot 失效,如-
,但Bracket
卻不會。myStruct.myNewKey = "my value";
,建立的key 不能有特殊字元,不會區分大小寫(對CF而言都是大寫)myStruct["myNewKey"] = "my value";
,建立的key可以有特殊字元,會區分大小寫structDelete(struct, "target", "true/false")
:
structDelete()
都只會回傳true<cfscript>
variables.structMadeOfWood = {
furniture = "chair",
face = "teeth",
Dutch = "shoes",
body ="your black heart"
};
writeDump(var=variables.structMadeOfWood);
writeOutput(structDelete(variables.structMadeOfWood, "body") & "<br/>");
writeOutput(structDelete(variables.structMadeOfWood, 99, false) & "<br/>");
writeOutput(structDelete(variables.structMadeOfWood, "tubthumpin") & "<br/>");
writeOutput(structDelete(variables.structMadeOfWood, "marmalade", true) & "<br/>");
writeDump(var=variables.structMadeOfWood);
</cfscript>
<cfset variables.structFootball = {
"quarterback" = "Russell Wilson",
"running_back" = "Marshawn Lynch",
"wide-receiver" = "Percy Harvin",
"cornerback" = "Richard Sherman"
}
/>
<h5>For-In Looping Results</h5>
<div><em>using tags</em></div>
<cfoutput>
<cfloop collection="#variables.structFootball#" item="variables.cur">
Our #variables.cur# is #variables.structFootball[variables.cur]#<br/>
</cfloop>
</cfoutput>
<hr/>
<div><em>using cfscript</em></div>
<cfscript>
for(variables.scriptCur in variables.structFootball) {
writeOutput("Our " & variables.scriptCur & " is " & variables.structFootball[variables.scriptCur] & "<br/>");
}
</cfscript>
sturctSort(struct, "type", "ASC/DESC")
不會改變struct,用 structSort
的函數取得的 array 其中包含排好順序的 struct keys
<cfset variables.structFootball = {
"quarterback" = "Russell Wilson",
"running_back" = "Marshawn Lynch",
"wide-receiver" = "Percy Harvin",
"cornerback" = "Richard Sherman"
}
/>
<cfset variables.arSortedKeys = structSort(variables.structFootball, "textnocase", "ASC") />
<h5>For-In Looping Results</h5>
<div><em>using tags</em></div>
<cfoutput>
<cfloop array="#variables.arSortedKeys#" index="variables.cur">
Our #variables.cur# #variables.structFootball[variables.cur]#<br/>
</cfloop>
</cfoutput>
<hr/>
<div><em>using cfscript</em></div>
<cfscript>
for(variables.scriptCur in variables.arSortedKeys) {
writeOutput("Our " & variables.scriptCur & " is " & variables.structFootball[variables.scriptCur] & "<br/>");
}
</cfscript>
variables.myString
就是使用 struct Dot Notation
structKeyExists()
: 確認 query column 是否存在在CFML query object
<cfscript>
writeDump(var=variables.qrySluff);
writeOutput("<hr/>Do we know if these people love dogs? " & structKeyExists (variables.qrySluff, "doglover") & "<br/>");
writeOutput("Do we know if these people love propane? " & structKeyExists (variables.qrySluff, "propanelover") & "<br/><br/>");
writeOutput("Ages<br/>");
for(variables.x=1; variables.x<= variables.qrySluff.recordCount; variables.x++) {
if(structKeyExists(variables.qrySluff, "age")) {
writeoutput(variables.qrySluff["age"][variables.x] & "<br/>");
}
}
</cfscript>
structKeyExists()
: 確認 component 的方法
component name="JellyBelly" accessors="true" {
property name="color" type="string";
}
variables.myJellyBean = new JellyBelly();
if(structKeyExists(variables.myJellyBean, "getColor")) {
writeOutput("my jelly's color is " & variables.myJellyBean.getColor() & ".");
}
Ref: Structures-in-ColdFusion Tutorials
<cffunction name="MyFirstFunction" returntype="boolean">
...
<cfreturn ... />
</cffunction>
<cfset results = MyFirstFunction()>
<cffunction name="SumNumbers" access="private" returntype="numeric">
<cfargument name="Num1" required="yes" type="numeric">
<cfargument name="Num2" required="yes" type="numeric">
<cfset result = Num1 + Num2>
<cfreturn result>
</cffunction>
<cfset result = SumNumbers(1,99) />
<cfoutput>#result#</cfoutput>
Ref: COLDFUSION - USER DEFINED FUNCTIONS Tutorials